package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.text.ParseException;
import java.util.Map;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    JedisPool jedisPool;

    @Reference
    OrderService orderService;


    /**
     * 提交预约
     *  1. 校验验证码，如果失败，返回页面
     *  2. 验证成功，调用预约服务
     *  3. 如果预约成功，发送短信给用户【 不能发送通知短信】
     * @return
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map<String,Object> map){
        // 校验验证码，如果失败，返回页面
        //1. 从map集合取出用户输入的验证码
        Object validateCodeObj = map.get("validateCode");
        String validateCode = String.valueOf(validateCodeObj);
        //2. 从redis中取出验证码
        //取出用户输入的手机号码
        Object telephoneObj = map.get("telephone");
        String telephone = String.valueOf(telephoneObj);
        String validateCodeInRedis = jedisPool.getResource().get(RedisMessageConstant.SENDTYPE_ORDER+"-"+telephone);
        //3. 开始校验
        if(validateCode == null || !validateCode.equals(validateCodeInRedis)){
            //校验失败,返回页面错误结果
            return  new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }else{
            //设置预约的类型
            map.put("orderType", Order.ORDERTYPE_WEIXIN);
            //检验成功,  调用预约服务
            Result result = null;
            try {
                result = orderService.addOrder(map);
            } catch (ParseException e) {
                e.printStackTrace();
                return  new Result(false, MessageConstant.ORDER_FAIL);
            }
            return result;
        }
    }

    /**
     * 根据id查询套餐信息
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map<String,Object> map = orderService.findById(id);
            return  new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
